package com.example.itshome.network;

import android.app.Activity;
import android.util.Log;
import android.widget.Toast;
import com.example.itshome.entity.MyInteger;
import com.example.itshome.entity.UserEntity;
import com.example.itshome.manager.UserInfoManager;
import com.example.itshome.util.ToastUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SendPostRequest extends AbstractNetworkRequest{

    private List<File> files;
    private String text;
    private int backId;


    public SendPostRequest setFiles(List<File> files) {
        this.files = files;
        return this;
    }

    public SendPostRequest setText(String text) {
        this.text = text;
        return this;
    }

    public SendPostRequest(Activity activity) {
        super(activity);
    }

    @Override
    protected String getPathAndParams() {
        return "moment/post?username="+ UserInfoManager.getInstance().getUser().getUsername()+
                "&text="+text;
    }

    @Override
    protected void handleResult(String result) {
        try{
            JSONObject jsonObject=new JSONObject(result);
            int code=jsonObject.getInt("code");
            if(code!=200){
                return;
            }
            backId= jsonObject.getInt("data");
            setHandleResultRunnable(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity,"发送成功",Toast.LENGTH_SHORT).show();
                    UserEntity user=UserInfoManager.getInstance().getUser();
                    user.setPostCount(user.getPostCount()+1);
                    user.setIntegral(user.getIntegral()+1);
                    UserInfoManager.getInstance().callRunner();
                    activity.finish();
                }
            });
        }catch (JSONException e){
            e.printStackTrace();
        }

    }

    @Override
    protected boolean canStart() {
        if(files.size()==0){
            ToastUtil.showToast("请选择图片",activity);
            return false;
        }else if(text.trim().length()<5){
            ToastUtil.showToast("至少输入5个字",activity);
            return false;
        }else if(text.length()>20){
            ToastUtil.showToast("请输入少于20个字",activity);
            return false;
        }
        return true;
    }

    @Override
    protected void afterResult() {
        for (int i=0;i<files.size();i++){
            Map<String,String> map=new HashMap<>();
            map.put("username",UserInfoManager.getInstance().getUser().getUsername());
            map.put("momentsId", String.valueOf(backId));
            map.put("picId",String.valueOf(i+1));
            UploadFileRequest.uploadForm(map,"file",files.get(i),"file/upload-moment-images",null);
        }

    }
}
